<?php
namespace addons\wwh\model;

use think\Db;
use think\Model;

class Column extends Model
{
    // 表名
    protected $name = 'wwh_column';

    /**
     * 获取顶级栏目
     */
    public static function getTopColumn($navCur)
    {
        if ($navCur['parent_id'] == 0) {
            return $navCur;
        }

        $top = self::where('id', $navCur['parent_id'])
            ->where('parent_id', 0)
            ->find();

        if (!$top) {
            // 如果父级不是顶级，继续向上查找
            $parentId = $navCur['parent_id'];
            while ($parentId != 0) {
                $parent = self::where('id', $parentId)->find();
                if ($parent['parent_id'] == 0) {
                    $top = $parent;
                    break;
                }
                $parentId = $parent['parent_id'];
            }
        }

        return $top ?: $navCur;
    }

    /**
     * 获取第二级栏目
     */
    public static function getSecondId($currentId)
    {
        $current = self::where('id', $currentId)
            ->field('parent_ids')
            ->find();

        if (!$current || empty($current['parent_ids'])) {
            return 0;
        }

        $parents = array_values(array_filter(
            explode(',', $current['parent_ids']),
            function($v) {
                return trim($v) !== '' && $v !== '0';
            }
        ));

        return $parents[1] ?? 0;
    }
}
